package com.COMP3111H.project;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Agreement extends Activity {
	String username;
	TextView para1, para2, para3, para4, para5;
	final int HELP = 0;
	
	ProgressThread progThread;
	final int SPINNER = 0;
	ProgressDialog progDialog;
	
	String paraHtml1 = "(1)All your information is accurate so that"
		    + " we could contact you. ";

	String paraHtml2 = "(2)If the book is not delivered by BookWarm,"
			+" your email address will be sent to the book"
			+" seller, and you will meet with the seller to"
			+" get the book.";

	String paraHtml3 = "3)Your other information provided will be"
			+" protected by BookWarm and will not be"
			+" revealed to any third party.";
	
	String paraHtml4 = "(4)If you are getting books owned by"
		    +" BookWarm and you wish to cancel your"
		    +" deal, please contact us at"
		    +" <b>book@bookwarm.org</b> ASAP. You may also"
		    +" cancel your deal after you check the book.";
	String paraHtml5 = "(5)If you could not pick up the book on your"
			+" selected date, please inform us one"
			+" day in advance. Otherwise, your reservation"
			+" will be canceled.";

	Button menu;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
			setContentView(R.layout.agreement);
			
			menu = (Button) findViewById(R.id.agreement_menu);
			menu.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					 String[] choices={"Home","View My Profile","Help","Cancel"};  
					             AlertDialog dialog = new AlertDialog.Builder(Agreement.this)  
					                     // .setIcon(android.R.drawable.btn_star)  
					                      .setTitle("Menu")  
					                      .setItems(choices, onselect_logged).create();  
					             dialog.show();  
				}
			});
			username = LoginUtility.getUsernamePassword(this)[0];
			
			final Bundle extras = this.getIntent().getExtras();
			
			(para1 = (TextView) findViewById(R.id.tvAgreePara1)).setText(Html
					.fromHtml(paraHtml1));
		
			(para2 = (TextView) findViewById(R.id.tvAgreePara2)).setText(Html
					.fromHtml(paraHtml2));
		
			(para3 = (TextView) findViewById(R.id.tvAgreePara3)).setText(Html
					.fromHtml(paraHtml3));
			
			(para4 = (TextView) findViewById(R.id.tvAgreePara4)).setText(Html
					.fromHtml(paraHtml4));
			
			(para5 = (TextView) findViewById(R.id.tvAgreePara5)).setText(Html
					.fromHtml(paraHtml5));
	
			Button disagree = (Button) findViewById(R.id.agreement_disagree);
			Button agree = (Button) findViewById(R.id.agreement_agree);
			agree.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	            	showDialog(SPINNER);
	    			progThread = new ProgressThread(handler, extras);
	    			progThread.start();
	            }
	        });
			
			disagree.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					finish();	
				}
			});
	}
	
	OnClickListener onselect_logged = new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			Intent myIntent;
			switch (which) {
			case 0:
				myIntent = new Intent(Agreement.this, Home.class);
				startActivity(myIntent);
				break;
			case 1:
				myIntent = new Intent(Agreement.this, My_Profile.class);
				startActivity(myIntent);
				break;
			case 2:
				myIntent = new Intent(Agreement.this, Help.class);
				startActivity(myIntent);
				break;
			case 3:
				dialog.dismiss();
				break;
			}
		}
	};

	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0: // Spinner
			progDialog = new ProgressDialog(this);
			progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progDialog.setMessage("Loading...");

			return progDialog;
		default:
			return null;
		}
	}

	// Handler on the main (UI) thread that will receive messages from the
	// second thread and update the progress.

	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			// Get the current value of the variable total from the message data
			// and update the progress bar.
			int from = msg.getData().getInt("from");
			String returnedData = msg.getData().getString("returnedData");
			removeDialog(SPINNER);		
			
			if(from == 1){
	    		if(returnedData.contains("user_not_logged_in")){
					Toast.makeText(Agreement.this,"Please log in first.", Toast.LENGTH_LONG).show();
				}
				else if(returnedData.contains("new_isbn_already_exists") ){
					Intent myIntent = new Intent(Agreement.this, Book_Already_Exist.class);
	            	startActivity(myIntent);  
				}
				else if(returnedData.contains("successful")){
					Intent myIntent = new Intent(Agreement.this, SellLend_Success.class);
	            	startActivity(myIntent);  
				}
				else{
					Toast.makeText(Agreement.this,"Network error. Please check your network connection.", Toast.LENGTH_SHORT).show();
				}
			}
			else if(from == 2){
	    			if(returnedData.contains("user_not_logged_in")){
					Toast.makeText(Agreement.this,"Please log in first.", Toast.LENGTH_LONG).show();
				}
				else if(returnedData.contains("insert_bookcopy_failed") || returnedData.contains("insert_sell_failed")){
					Toast.makeText(Agreement.this,"Transaction failed.", Toast.LENGTH_SHORT).show();
				}
				else if(returnedData.contains("insert_successful")){
					Intent myIntent = new Intent(Agreement.this, SellLend_Success.class);
	            	startActivity(myIntent);  
				}
				else{
					Toast.makeText(Agreement.this,"Network error. Please check your network connection.", Toast.LENGTH_SHORT).show();
				}
			}
			else if(from == 3){
				if(returnedData.contains("user_not_logged_in")){
    				Toast.makeText(Agreement.this,"Please log in first.", Toast.LENGTH_LONG).show();
    			}
    			else if(returnedData.contains("seller_cannot_buy")){
    				Toast.makeText(Agreement.this,"Sorry, you cannot buy your own book.", Toast.LENGTH_LONG).show();
    			}
    			else if(returnedData.contains("insert_successful")){
    				Intent myIntent = new Intent(Agreement.this, BuyBorrow_Success_Page.class);
    				startActivity(myIntent);
    			}
    			else if(returnedData.contains("insert_failed")){
    				Toast.makeText(Agreement.this,"Transaction failed.", Toast.LENGTH_LONG).show();
    			}
    			else{
    				Toast.makeText(Agreement.this,"Network error. Please check your network connection.", Toast.LENGTH_LONG).show();
    			}
			}
			else if(from == 4){
				if(returnedData.contains("user_not_logged_in")){
    				Toast.makeText(Agreement.this,"Please log in first.", Toast.LENGTH_SHORT).show();
    			}
    			else if(returnedData.contains("insert_bookcopy_failed") || returnedData.contains("update_credit_failed")){
    				Toast.makeText(Agreement.this,"Transaction failed.", Toast.LENGTH_SHORT).show();
    			}
    			else if(returnedData.contains("insert_successful")){
    				Intent myIntent = new Intent(Agreement.this, SellLend_Success.class);
    				startActivity(myIntent);
    			}
    			else{
    				Toast.makeText(Agreement.this,"Network error. Please check your network connection.", Toast.LENGTH_SHORT).show();
    			}
			}
			else if(from == 5){
				if(returnedData.contains("user_not_logged_in")){
    				Toast.makeText(Agreement.this,"Please log in first.", Toast.LENGTH_SHORT).show();
    			}
    			else if(returnedData.contains("new_isbn_already_exists") ){
    				Intent myIntent = new Intent(Agreement.this, Book_Already_Exist.class);
	            	startActivity(myIntent); 	
    			}
    			else if(returnedData.contains("insert_successful")){
    				Intent myIntent = new Intent(Agreement.this, SellLend_Success.class);
    				startActivity(myIntent);
    			}
    			else{
    				Toast.makeText(Agreement.this,"Network error. Please check your network connection.", Toast.LENGTH_SHORT).show();
    			}
			}
			else if(from == 6){
				if(returnedData.contains("user_not_logged_in")){
					Toast.makeText(Agreement.this,"Please log in first.", Toast.LENGTH_SHORT).show();
				}
				else if(returnedData.contains("new_isbn_already_exists")){
					Intent myIntent = new Intent(Agreement.this, Book_Already_Exist.class);
	            	startActivity(myIntent); 
				}
				else if(returnedData.contains("insert_successful")){
					Intent myIntent = new Intent(Agreement.this, SellLend_Success.class);
    				startActivity(myIntent);
				}
				else{
					Toast.makeText(Agreement.this,"Network error. Please check your network connection.", Toast.LENGTH_SHORT).show();
				}
			}
			else if(from == 7){
				if(returnedData.contains("user_not_logged_in")){
					Toast.makeText(Agreement.this,"Please log in first.", Toast.LENGTH_SHORT).show();
				}
				else if(returnedData.contains("new_isbn_already_exists") ){
					Intent myIntent = new Intent(Agreement.this, Book_Already_Exist.class);
	            	startActivity(myIntent); 	
				}
				else if(returnedData.contains("insert_successful")){
					Intent myIntent = new Intent(Agreement.this, SellLend_Success.class);
    				startActivity(myIntent);
				}
				else{
					Toast.makeText(Agreement.this,"Network error. Please check your network connection.", Toast.LENGTH_SHORT).show();
				}
			}
			else if(from == 8){
				if(returnedData.contains("user_not_logged_in")){
    				Toast.makeText(Agreement.this,"Please log in first.", Toast.LENGTH_SHORT).show();
    			}
				else if(returnedData.contains("lender_cannot_borrow")){
    				Toast.makeText(Agreement.this,"Sorry, you cannot borrow your own book.", Toast.LENGTH_LONG).show();
    			}
    			else if(returnedData.contains("insert_successful")){
    				Intent myIntent = new Intent(Agreement.this, BuyBorrow_Success_Page.class);
    				startActivityForResult(myIntent,1);
    			}
    			else if(returnedData.contains("insert_failed")){
    				Toast.makeText(Agreement.this,"Transaction failed.", Toast.LENGTH_SHORT).show();
    			}
    			else if(returnedData.contains("insufficient_credit")){ 
    				 Intent i = new Intent(Agreement.this,No_Credit.class); 
    				 startActivity(i); 
    				 } 
    			else{
    				Toast.makeText(Agreement.this,"Network error. Please check your network connection.", Toast.LENGTH_SHORT).show();
				}
			}
		}
	};

	private class ProgressThread extends Thread {
		// Class constants defining state of the thread
		Handler mHandler;
		Bundle extras;

		ProgressThread(Handler h, final Bundle e) {
			mHandler = h;
			extras = e;
		}

		@Override
		public void run() {
			Message msg = mHandler.obtainMessage();
			if(extras.getInt("origin")==0)
        	{
        		String returnedData;
        		String isbn = extras.getString("isbn");
        		String price = extras.getString("price");
        		String condition = extras.getString("condition");
        		
        		if(extras.getBoolean("changeEdition"))
        		{
        			// (String old_isbn, String new_isbn, String user_name, String copy_condition, int copy_price, int edition)
        			List<NameValuePair> params = new ArrayList<NameValuePair>(6);
        			params.add(new BasicNameValuePair("username", username));
        			params.add(new BasicNameValuePair("oldisbn", isbn));
        			params.add(new BasicNameValuePair("newisbn", extras.getString("newisbn")));
        			params.add(new BasicNameValuePair("edition", Integer.toString(extras.getInt("newEdition"))));
        			params.add(new BasicNameValuePair("copycondition", condition));
        			params.add(new BasicNameValuePair("copyprice", price));
        			
        			returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/sell_new_edition.jsp");
        			Bundle b = new Bundle();
    				b.putString("returnedData", returnedData);
    				b.putInt("from", 1);
    				msg.setData(b);
    				mHandler.sendMessage(msg);
        		}
        		else{
        			List<NameValuePair> params = new ArrayList<NameValuePair>(4);
        			params.add(new BasicNameValuePair("username", username));
        			params.add(new BasicNameValuePair("isbn", isbn));
        			params.add(new BasicNameValuePair("copycondition", condition));
        			params.add(new BasicNameValuePair("copyprice", price));
        			returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/sell_existing.jsp");
        			Bundle b = new Bundle();
    				b.putString("returnedData", returnedData);
    				b.putInt("from", 2);
    				msg.setData(b);
    				mHandler.sendMessage(msg);		
        		}
        	}
        	// if the origin comes from *BUY*
        	else if (extras.getInt("origin")==1)
        	{
        		String copyid = extras.getString("copyid");
        		
        		List<NameValuePair> params = new ArrayList<NameValuePair>(2);
        		params.add(new BasicNameValuePair("copyid", copyid));
        		params.add(new BasicNameValuePair("username", username));
        		
        		String returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/buyinsert.jsp");
        		Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("from", 3);
				msg.setData(b);
				mHandler.sendMessage(msg);		
        	}
        	else if (extras.getInt("origin")==2){
        		//TODO
        		//if the origin comes from *Lend*
        		String isbn = extras.getString("isbn");
        		String copycondition = extras.getString("condition");
        		String returnedData;
        		if(!extras.getBoolean("changeEdition")){
        			List<NameValuePair> params = new ArrayList<NameValuePair>(2);
        			params.add(new BasicNameValuePair("username", username));
        			params.add(new BasicNameValuePair("isbn", isbn));
        			params.add(new BasicNameValuePair("copycondition", copycondition));
        			returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/lend_existing.jsp");
        			Bundle b = new Bundle();
    				b.putString("returnedData", returnedData);
    				b.putInt("from", 4);
    				msg.setData(b);
    				mHandler.sendMessage(msg);
        		}
        		else{
        			String newEdition = extras.getString("newEdition");
        			String newisbn = extras.getString("newisbn");
        			Log.v("Bookwarm",username + "," + isbn + "," +newisbn + "," + newEdition + "," + copycondition);
        			List<NameValuePair> params = new ArrayList<NameValuePair>(5);
        			params.add(new BasicNameValuePair("username", username));
        			params.add(new BasicNameValuePair("oldisbn", isbn));
        			params.add(new BasicNameValuePair("newisbn", newisbn));
        			params.add(new BasicNameValuePair("edition", newEdition));
        			params.add(new BasicNameValuePair("copycondition", copycondition));
        			returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/lend_new_edition.jsp");
        			Bundle b = new Bundle();
    				b.putString("returnedData", returnedData);
    				b.putInt("from", 5);
    				msg.setData(b);
    				mHandler.sendMessage(msg);
        		}
        	}
        	else if (extras.getInt("origin")==3){
        		//origin comes from *SELL/LEND NEW BOOK*
        		String title = extras.getString("title");
				String courses = extras.getString("courses");
				String authors = extras.getString("authors");
				String edition = extras.getString("edition");
				String isbn = extras.getString("isbn");
				String condition = extras.getString("condition");
				String selllend = extras.getString("selllend");
				String publisher = extras.getString("publisher");
				String returnedData;
				if(selllend.matches("lend")){
					//TODO
					List<NameValuePair> params = new ArrayList<NameValuePair>(8);
					params.add(new BasicNameValuePair("username", username));
					params.add(new BasicNameValuePair("isbn", isbn));
					params.add(new BasicNameValuePair("edition", edition));

					params.add(new BasicNameValuePair("copycondition", condition));
					params.add(new BasicNameValuePair("booktitle", title));
					params.add(new BasicNameValuePair("courses", courses));
					params.add(new BasicNameValuePair("authors", authors));
					params.add(new BasicNameValuePair("publisher", publisher));
					
					returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/lend_new_book.jsp");			
					Bundle b = new Bundle();
    				b.putString("returnedData", returnedData);
    				b.putInt("from", 6);
    				msg.setData(b);
    				mHandler.sendMessage(msg);
				}
				else if(selllend.matches("sell")){
					String copyprice = extras.getString("price");
					List<NameValuePair> params = new ArrayList<NameValuePair>(9);
					params.add(new BasicNameValuePair("username", username));
					params.add(new BasicNameValuePair("isbn", isbn));
					params.add(new BasicNameValuePair("edition", edition));
					params.add(new BasicNameValuePair("copycondition", condition));
					params.add(new BasicNameValuePair("booktitle", title));
					params.add(new BasicNameValuePair("courses", courses));
					params.add(new BasicNameValuePair("authors", authors));
					params.add(new BasicNameValuePair("publisher", publisher));
					params.add(new BasicNameValuePair("copyprice",copyprice));
					returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/sell_new_book.jsp");
					Bundle b = new Bundle();
    				b.putString("returnedData", returnedData);
    				b.putInt("from", 7);
    				msg.setData(b);
    				mHandler.sendMessage(msg);
				}
        	}
        	// if the origin comes from *BORROW*
        	else 
        	{
        		String copyid = extras.getString("copyid");
        		List<NameValuePair> params = new ArrayList<NameValuePair>(2);
        		params.add(new BasicNameValuePair("copyid", copyid));
        		params.add(new BasicNameValuePair("username", username));
        		
        		String returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/borrowinsert.jsp");
        		Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("from", 8);
				msg.setData(b);
				mHandler.sendMessage(msg);
        	}
		}
	}
}

